package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.bean.PageRes;
import com.example.demo.bean.log.SysLoginLogDO;
import com.example.demo.exception.OtherException;
import com.example.demo.mapper.log.SysLoginLogMapper;
import com.example.demo.service.ISysLoginLogService;
import com.example.demo.dto.log.SysLoginLogPageReqVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class SysLoginLogServiceImpl extends ServiceImpl<SysLoginLogMapper, SysLoginLogDO> implements ISysLoginLogService {

    @Resource
    private SysLoginLogMapper sysLoginLogMapper;

    @Override
    public PageRes<SysLoginLogDO> list(SysLoginLogPageReqVO sysLoginLogPageReqVO) {
        return sysLoginLogMapper.selectPage(sysLoginLogPageReqVO);
    }

    @Override
    public void addSysLoginLog(SysLoginLogDO sysLoginLogDO) {
        sysLoginLogMapper.insert(sysLoginLogDO);
    }

    @Override
    public int deleteLoginLog(Long[] logIds) {
        int deleteCount = 0;
        for (Long logId : logIds) {
            validExist(logId);
            deleteCount += sysLoginLogMapper.deleteById(logId);
        }
        return deleteCount;
    }

    @Override
    public void clearLoginLog() {
        sysLoginLogMapper.delete(new QueryWrapper<>());
    }

    private void validExist(Long logId) {
        SysLoginLogDO exist = sysLoginLogMapper.selectById(logId);
        if (exist == null) {
            throw new OtherException("登录日志不存在");
        }
    }
}
